<?php
function AttrListFolderData($mes) {
  global $_GET, $path, $style, $session_id, $data, $term_Thing_ID, $language, $header;
  $filename = $path[$style]["tpl"]."/attrdata.xml";
  $fp = fopen($filename, "r");
  $contents = fread($fp, filesize ($filename));
  fclose ($fp);

  preg_match("/\%REPEAT\%(.*?)\%REPEAT\%/s", $contents, $matches);
  preg_match("/\%REPDAT\%(.*?)\%REPDAT\%/s", $matches[1], $datmatches);

  $udata = str_replace($datmatches[0], "", $matches[1]);
  $udata = str_replace("%GROUP_ID%", "0", $udata);
  $udata = str_replace("%GROUP_TL%", $mes, $udata);
  $contents = str_replace("%DatHref%", "index.php?trg=ontoedit&amp;act=attrlistdata&amp;sid=".
      $session_id."&amp;uid=".$_GET["uid"], $contents);
  header ($header["xml"]);
  return str_replace($matches[0], $udata, $contents);
}

function attrList($inputoutput){
 global $_GET, $data, $path, $style, $session_id, $language, $header;
  $filename = $path[$style]["tpl"]."/classes.xml";
  $fp = fopen($filename, "r");
  $contents = fread($fp, filesize ($filename));
  fclose ($fp);

  preg_match("/\%REPEAT\%(.*?)\%REPEAT\%/s", $contents, $matches);
  $rep_cont = "";
  //echo $_GET["uid"]."<br>";
  $classID = substr($_GET["uid"], 1);

/*  $sql_str = "SELECT o.type_id FROM class c, ontology o WHERE c.id=".$classID." and o.id=c.onto_id";
  getData($sql_str, $iotype);
  if ($iotype["type_id"] == 2)
*/
  $rep_cont = getAttributes($classID, $matches[1], 1, $inputoutput);
  $contents = str_replace($matches[0], $rep_cont, $contents);
  header ($header["xml"]);

  return $contents;
};

function getAttributes($classID, $contents, $ret_data, $inputoutput) {
  global $_GET, $data, $path, $session_id, $language, $header;
  $attrs = array();
  $hash = array();
  $i_max = getParentAttributes($classID, $attrs, $hash, 0, $ret_data, $inputoutput);
  if ($ret_data == 0) return $i_max;
  if (sizeof($attrs) == 0) return "";
  uasort($attrs, 'Compare');
  $res_str = "";
  $tmp_cont = "";
  reset($attrs);
  $i = 0;
  while (list ($key, $attr) = each ($attrs)) {
    if ($inputoutput == 0)
      $tmp_cont = str_replace("%CLASS_ID%", "a".$classID."a".$attr["id"], $contents);
    if ($inputoutput == 1)
      $tmp_cont = str_replace("%CLASS_ID%", "ia".$classID."ia".$attr["id"], $contents);
    if ($inputoutput == 2)
      $tmp_cont = str_replace("%CLASS_ID%", "oa".$classID."oa".$attr["id"], $contents);
    $tmp_cont = str_replace("%CLASS_NM%", $attr["name"], $tmp_cont);
    if ($attr["inhrtd"] == 0) $tmp_cont = str_replace("%IMG_TYPE%", "attr", $tmp_cont);
    else $tmp_cont = str_replace("%IMG_TYPE%", "inhattr", $tmp_cont);


    if (isset($_GET["bound"]))
      $bound=$_GET["bound"];
    else
      $bound="false";


    if ($inputoutput == 0){
      $tmp_cont = str_replace("%CLASS_LN%", "index.php?trg=ontoedit&amp;act=attrdata&amp;sid=".
        $session_id."&amp;uid=a".$classID."a".$attr["id"]."&amp;bound=".$bound, $tmp_cont);
      if ($_GET["sel"] == "a".$classID."a".$attr["id"])
        $tmp_cont = str_replace("%ACT%", "select", $tmp_cont);
    };
    if ($inputoutput == 1){
      $tmp_cont = str_replace("%CLASS_LN%", "index.php?trg=ontoedit&amp;act=attrdata&amp;sid=".
        $session_id."&amp;uid=ia".$classID."ia".$attr["id"], $tmp_cont);
      if ($_GET["sel"] == "ia".$classID."ia".$attr["id"])
        $tmp_cont = str_replace("%ACT%", "select", $tmp_cont);
    };
    if ($inputoutput == 2){
      $tmp_cont = str_replace("%CLASS_LN%", "index.php?trg=ontoedit&amp;act=attrdata&amp;sid=".
        $session_id."&amp;uid=oa".$classID."oa".$attr["id"], $tmp_cont);
      if ($_GET["sel"] == "oa".$classID."oa".$attr["id"])
        $tmp_cont = str_replace("%ACT%", "select", $tmp_cont);
    };

      if (isset($_GET["sel"]) &&
        ($_GET["sel"] == "a".$classID."a".$attr["id"] ||
        ($_GET["sel"] == 0 && $i == 0))) {
        $tmp_cont = str_replace("%ACT%", "select", $tmp_cont);
      }

// Alignments
    $sql_tmp = "SELECT type_id FROM ontology WHERE id = (SELECT onto_id FROM class WHERE id = ".substr($_GET["uid"], 1).")";
    $ontotype = Array();
    getData($sql_tmp, $ontotype);

    $sql_tmp = "SELECT type_id FROM ontology WHERE id = (SELECT base_onto_id FROM class WHERE id = ".substr($_GET["uid"], 1).")";
    $base_onto_type = Array();
    getData($sql_tmp, $base_onto_type);

    if ((($ontotype["type_id"] == 5)&&($base_onto_type["type_id"] == 3))||(($ontotype["type_id"] == 0)&&(($base_onto_type["type_id"] == 1)||($base_onto_type["type_id"] == 2)))){
      $sql_tmp = "SELECT type_id FROM ontology WHERE id = (SELECT base_onto_id FROM class WHERE id = ".substr($_GET["uid"], 1).")";
      $ontotype = Array();
      getData($sql_tmp, $ontotype);
      //echo $ontotype["type_id"]."<br>";
      if (($ontotype["type_id"] == 3)||($ontotype["type_id"] == 1)||($ontotype["type_id"] == 2)){
        //if (getAlignment($attr["id"], $matches, $session_id) != "")
          $tmp_cont = str_replace("%CHILD_LN%", "index.php?trg=ontoedit&amp;act=attralignment&amp;sid=".
            $session_id."&amp;uid=al".$attr["id"], $tmp_cont);
      };
    };

    $tmp_cont = str_replace("%CHILD_LN%", "", $tmp_cont);
    $res_str .= $tmp_cont;
    $i++;
  }
  return $res_str;
}

function getParentAttributes($classID, &$attrs, &$hash, $inherited, $ret_data, $inputoutput) {
  global $_GET, $data, $path, $session_id, $language, $header;
  $sql_str = "SELECT attr.id as id, term.text as name, ".$inherited." as inhrtd ".
    "FROM attr, term, class_attr ".
    "WHERE class_attr.class_id = ".$classID." and attr.Type = ".$inputoutput.
    " AND class_attr.attr_id = attr.id AND attr.term_id = term.id AND term.lang_id = ".$language["content"].
    " ORDER BY term.text;";

  $i_max = getMultData($sql_str, $ontosdata);
  //print ("Class: ".$classID." Attrs: ".$i_max." Ret: ".$ret_data."; ");
  if ($i_max > 0 && $ret_data == 0) return 1;
  for ($i = 0; $i < $i_max; $i++) {
    if (!isset($hash[$ontosdata[$i]["id"]])) {
      //print ("New attr: ".$ontosdata[$i]["id"]."; ");
      $hash[$ontosdata[$i]["id"]] = sizeof($attrs);
      $attrs[sizeof($attrs)] = $ontosdata[$i];
    }
    else {
      //print ("Got attr: ".$ontosdata[$i]["id"]."; ");
      $attrs[$hash[$ontosdata[$i]["id"]]]["inhrtd"] = "1";
    }
  }
  $sql_str = "SELECT parent_id FROM class WHERE id = ".$classID.";";
  if (getData($sql_str, $p_class) == 1 && $p_class["parent_id"] != 0) {
    if (getParentAttributes($p_class["parent_id"], $attrs, $hash, 1, $ret_data, $inputoutput) > 0) {
      if ($ret_data == 0) return 1;
    }
  }
  return $i_max;
}

function attrData() {
  global $_GET, $data, $path, $style, $session_id, $header;

  if (substr($_GET["uid"],0 , 1) == "a"){
    $_GET["uid"] = substr($_GET["uid"], 1);
    $ID = explode("a", $_GET["uid"]);
  };

  if (substr($_GET["uid"],0 , 2) == "ia"){
    $_GET["uid"] = substr($_GET["uid"], 2);
    $ID = explode("ia", $_GET["uid"]);
  };

  if (substr($_GET["uid"],0 , 2) == "oa"){
    $_GET["uid"] = substr($_GET["uid"], 2);
    $ID = explode("oa", $_GET["uid"]);
  };
  $contents = getAttrData($ID, "", "false");
  header ($header["xml"]);
  return $contents;
}

function getAttrClass($classID, $attrID) {
  $out_data["classID"] = $classID;
  $out_data["attr_class_ID"] = 0;
  $sql_str = "SELECT id FROM class_attr WHERE class_id = ".$classID." AND attr_id = ".$attrID.";";
  if (getData($sql_str, $attr_class_id) == 1) $out_data["attr_class_ID"] = $attr_class_id["id"];
  else {
    $sql_str = "SELECT parent_id FROM class WHERE id = ".$classID.";";
    if (getData($sql_str, $p_class) == 1 && $p_class["parent_id"] != 0) {
      $out_data = getAttrClass($p_class["parent_id"], $attrID);
    }
  }
  return $out_data;
}

function updateAttr() {
  global $_GET, $data, $path, $style, $session_id, $term_Thing_ID, $language, $header, $accent_path, $accent_lang;
  //include "settings.php";
  include "stemming.php";
  if (substr($_GET["uid"],0 , 1) == "a"){
    $_GET["uid"] = substr($_GET["uid"], 1);
    $ID = explode("a", $_GET["uid"]);
  };

  if (substr($_GET["uid"],0 , 2) == "ia"){
    $_GET["uid"] = substr($_GET["uid"], 2);
    $ID = explode("ia", $_GET["uid"]);
  };

  if (substr($_GET["uid"],0 , 2) == "oa"){
    $_GET["uid"] = substr($_GET["uid"], 2);
    $ID = explode("oa", $_GET["uid"]);
  };
  $bound = "false";

  //Bound
  if (isset($_GET["oFeasibleMin"]) && isset($_GET["oRecomendedMin"]) && isset($_GET["oRecomendedMax"]) && isset($_GET["oFeasibleMax"])){
    $bound = "true";
    $_GET["oFeasibleMin"]=utf8Encode($_GET["oFeasibleMin"]);
    $_GET["oRecomendedMin"]=utf8Encode($_GET["oRecomendedMin"]);
    $_GET["oRecomendedMax"]=utf8Encode($_GET["oRecomendedMax"]);
    $_GET["oFeasibleMax"]=utf8Encode($_GET["oFeasibleMax"]);
    if (($_GET["oFeasibleMin"] <= $_GET["oRecomendedMin"]) && ($_GET["oRecomendedMin"] <= $_GET["oRecomendedMax"]) && ($_GET["oRecomendedMax"] <= $_GET["oFeasibleMax"]) && $_GET["oFeasibleMin"] >= -32768 && $_GET["oFeasibleMax"]< 32768 && $_GET["oFeasibleMin"]!="" && $_GET["oFeasibleMax"]!=" "){
      $sql_tmp = "SELECT id FROM CAD_Bounds WHERE ClassID=".$ID[0]." and AttrID=".$ID[1]." and Type=1";
      $bounds_list = Array();
      getData($sql_tmp, $bounds_list);
      if (count($bounds_list) == 0){
        $sql_str = "INSERT INTO CAD_Bounds (ClassID, AttrID, LeftBound, RightBound, Type) VALUES (".$ID[0].", ".$ID[1].", ".$_GET["oRecomendedMin"].", ".$_GET["oRecomendedMax"].", 1)";
        insertRecord($sql_str);
      }else{
        $sql_str = "UPDATE CAD_Bounds SET LeftBound=".$_GET["oRecomendedMin"].", RightBound=".$_GET["oRecomendedMax"].
          " WHERE id = ".$bounds_list["id"].";";
        insertRecord($sql_str);
      };
      $sql_tmp = "SELECT id FROM CAD_Bounds WHERE ClassID=".$ID[0]." and AttrID=".$ID[1]." and Type=2";
      $bounds_list = Array();
      getData($sql_tmp, $bounds_list);
      if (count($bounds_list) == 0){
        $sql_str = "INSERT INTO CAD_Bounds (ClassID, AttrID, LeftBound, RightBound, Type) VALUES (".$ID[0].", ".$ID[1].", ".$_GET["oFeasibleMin"].", ".$_GET["oFeasibleMax"].", 2)";
        insertRecord($sql_str);
      }else{
        $sql_str = "UPDATE CAD_Bounds SET LeftBound=".$_GET["oFeasibleMin"].", RightBound=".$_GET["oFeasibleMax"].
          " WHERE id = ".$bounds_list["id"].";";
        insertRecord($sql_str);
      };
    };
  };

  $comment = "";
  if ($data["type"] >= 1 && isset($_GET["oname"]) && isset($_GET["odescr"])) {
    $sql_tmp = "SELECT type_id FROM ontology WHERE id = (SELECT onto_id FROM class WHERE id = ".$ID[0].")";
    $ontotype = Array();
    getData($sql_tmp, $ontotype);
    if (!($ontotype["type_id"] == "5")){
      $_GET["oname"] = utf8Encode($_GET["oname"]);
      $_GET["odescr"] = utf8Encode($_GET["odescr"]);
      if (isset($_GET["otype"])) $_GET["otype"] = utf8Encode($_GET["otype"]);
      else $_GET["otype"] = 0;
      $attr_data = getAttrClass($ID[0], $ID[1]);
      if ($ID[0] == $attr_data["classID"] && $_GET["otype"] > 0) {
          $sql_str = "UPDATE class_attr SET class_attr.domtype_id = ".$_GET["otype"].
            " WHERE id = ".$attr_data["attr_class_ID"].";";
          insertRecord($sql_str);
      }
      getData("SELECT term_id FROM attr WHERE id = ".$ID[1].";", $ontoterm);
      if ($_GET["oname"] == "") {
        $comment = getMessage("EmptyName");
      } else {
  //echo $accent_path;
  //die("yes");
        $stem_text = stemming($_GET["oname"], $accent_path, $accent_lang);
        $stem_descr = stemming($_GET["odescr"], $accent_path, $accent_lang);

        $sql_str = "UPDATE term SET term.text = '".$_GET["oname"].
          "', term.description = '".$_GET["odescr"].
          "', term.stem_text = '".$stem_text."', term.stem_description = '".$stem_descr.
          "' WHERE term.id = ".$ontoterm["term_id"].
          " AND term.lang_id = ".$language["content"].";";
        insertRecord($sql_str);
      }
    }
  }
  // add domain to the enumerable
  if (isset($_GET["onewdom"])) {
    $_GET["onewdom"] = utf8Encode($_GET["onewdom"]);
    $sql = "SELECT id FROM class_attr WHERE class_id=".$ID[0]." and attr_id = ".$ID[1];
    getData($sql, $class_attr_id);
    $sql_tmp = "SELECT id FROM domtype_collection WHERE CollectionItem = '".$_GET["onewdom"]."' and lang_id = ".$language["content"]." and class_attr_id = ".$class_attr_id["id"];
    $i_max = getMultData($sql_tmp, $thesamecollections);
    if ($i_max == 0){
      $sql = "INSERT INTO domtype_collection (class_attr_id, CollectionItem, lang_id) VALUES (".$class_attr_id["id"].", '".$_GET["onewdom"]."', ".$language["content"].")";
      insertRecord($sql);
    };
  };

  // delete domain from the enumerable list
  if (isset($_GET["olistbox"])) {
    $_GET["olistbox"] = utf8Encode($_GET["olistbox"]);
    if ($_GET["olistbox"] > 0){
      $sql = "DELETE FROM domtype_collection WHERE id = ".$_GET["olistbox"];
      insertRecord($sql);
    };
  };

  $contents = getAttrData($ID, $comment, $bound);
  header ($header["xml"]);
  return $contents;
}

function createAttr() {
  global $_GET, $data, $path, $style, $session_id, $language;
  if (strrpos(substr($_GET["uid"], 1), "a")==false)
    $_GET["uid"] = substr($_GET["uid"], 1);
  else
    $_GET["uid"] = substr($_GET["uid"], 1, strrpos($_GET["uid"], "a")-1);

  if ($data["type"] >= 1) { //user
    $filename = $path[$style]["tpl"]."/action.xml";
    $fp = fopen($filename, "r");
    $contents = fread($fp, filesize ($filename));
    fclose ($fp);
    preg_match("/\%REPEAT\%(.*?)\%REPEAT\%/s", $contents, $matches);

    $sql_tmp = "SELECT type_id FROM ontology WHERE id = (SELECT onto_id FROM class WHERE id = ".$_GET["uid"].")";
    $ontotype = Array();
    getData($sql_tmp, $ontotype);
    if (!($ontotype["type_id"] == "5")){
      if (getData("SELECT onto_id FROM class where id = ".$_GET["uid"].";", $odatatmp) != 1) return "";

      $sql_str = "INSERT INTO term ([lang_id], [text], [description]) VALUES(".
        $language["content"].",'".
        $session_id."','".$session_id."');";
      //print ($sql_str);
      insertRecord($sql_str);
      if (getData("SELECT id FROM term where text = '".
        $session_id."' AND description = '".$session_id.
        "' AND term.lang_id = ".$language["content"].
        ";", $datatmp) == 1) {
        $sql_str = "UPDATE term SET term.text = '".getMessage("Name").
          "', term.description = '".getMessage("Description").
          "' WHERE term.id=".$datatmp["id"].
          " AND term.lang_id = ".$language["content"].";";
        insertRecord($sql_str);
        //print ($sql_str);
        insertRecord("INSERT INTO attr (onto_id, baseonto_id, term_id, session_id) VALUES(".
          $odatatmp["onto_id"].", 0, ".
          $datatmp["id"].", '".
          $session_id."');");
        if (getData("SELECT id FROM attr where session_id = '".
          $session_id."';", $datatmp) == 1) {
          $sql_str = "UPDATE attr SET attr.session_id = '' WHERE id=".
          $datatmp["id"].";";
          insertRecord($sql_str);
          $sql_str = "INSERT INTO class_attr (class_id, attr_id, domtype_id, min, max, limited, session_id) VALUES(".
            $_GET["uid"].", ".
            $datatmp["id"].", 1, 0, 0, 0, '".
            $session_id."');";
          //print($sql_str);
          insertRecord($sql_str);
          //print($sql_str);
          if (getData("SELECT id FROM class_attr WHERE session_id = '".
            $session_id."';", $datatmp) == 1) {
            $sql_str = "UPDATE class_attr SET class_attr.session_id = '' WHERE id=".
            $datatmp["id"].";";
            insertRecord($sql_str);
            $contents = str_replace("%SCCSS%", "1", $contents);
          } else {
            $contents = str_replace("%SCCSS%", "-1", $contents);
            $datatmp["id"] = 0;
          }
        } else {
          $contents = str_replace("%SCCSS%", "0", $contents);
          $datatmp["id"] = 0;
        }
      } else {
        $contents = str_replace("%SCCSS%", "0", $contents);
        $datatmp["id"] = 0;
      }
    }else{
      $contents = str_replace("%SCCSS%", "0", $contents);
      $datatmp["id"] = 0;
    }
  } else {
    $contents = str_replace("%SCCSS%", "0", $contents);
    $datatmp["id"] = 0;
  }
  $tmp_cont = str_replace("%NODE_ID%", "a".$_GET["uid"]."a".$datatmp["id"], $matches[1]);
  $tmp_cont = str_replace("%NODE_NM%", getMessage("Name"), $tmp_cont);
  $tmp_cont = str_replace("%IMG_TYPE%", "attr", $tmp_cont);
  $tmp_cont = str_replace("%NODE_LN%", "index.php?trg=ontoedit&amp;act=classdata&amp;sid=".
    $session_id."&amp;uid=a".$datatmp["id"], $tmp_cont);
  $contents = str_replace($matches[0], $tmp_cont, $contents);
  $contents = str_replace("%XMLSRC%", "index.php?trg=ontoedit&amp;act=attrlist&amp;sid=".
    $session_id."&amp;uid=a".$_GET["uid"]."&amp;sel=a".$_GET["uid"]."a".$datatmp["id"], $contents);
  $contents = str_replace("%ACT_ID%", "Add", $contents);
  $contents = str_replace("%PARENT%", "a".$_GET["uid"], $contents);
  return $contents;
}

function createIOAttr($inputoutput) {
  global $_GET, $data, $path, $style, $session_id, $language;
  if ($inputoutput == 1){
    if (strrpos(substr($_GET["uid"], 2), "ia")==false)
      $_GET["uid"] = substr($_GET["uid"], 2);
    else
      $_GET["uid"] = substr($_GET["uid"], 2, strrpos($_GET["uid"], "ia")-2);
  };
  if ($inputoutput == 2){
    if (strrpos(substr($_GET["uid"], 2), "oa")==false)
      $_GET["uid"] = substr($_GET["uid"], 2);
    else
      $_GET["uid"] = substr($_GET["uid"], 2, strrpos($_GET["uid"], "oa")-2);
  };
  if ($data["type"] >= 1) { //user
    $filename = $path[$style]["tpl"]."/action.xml";
    $fp = fopen($filename, "r");
    $contents = fread($fp, filesize ($filename));
    fclose ($fp);
    preg_match("/\%REPEAT\%(.*?)\%REPEAT\%/s", $contents, $matches);

    if (getData("SELECT onto_id FROM class where id = ".$_GET["uid"].";", $odatatmp) != 1) return "";
    $sql_str = "INSERT INTO term ([lang_id], [text], [description]) VALUES(".
      $language["content"].",'".
      $session_id."','".$session_id."');";
    //print ($sql_str);
    insertRecord($sql_str);
    if (getData("SELECT id FROM term where text = '".
      $session_id."' AND description = '".$session_id.
      "' AND term.lang_id = ".$language["content"].
      ";", $datatmp) == 1) {
      $sql_str = "UPDATE term SET term.text = '".getMessage("Name").
        "', term.description = '".getMessage("Description").
        "' WHERE term.id=".$datatmp["id"].
        " AND term.lang_id = ".$language["content"].";";
      insertRecord($sql_str);
      //print ($sql_str);
      insertRecord("INSERT INTO attr (onto_id, baseonto_id, term_id, session_id, Type) VALUES(".
        $odatatmp["onto_id"].", 0, ".
        $datatmp["id"].", '".
        $session_id."', ".$inputoutput.");");
      if (getData("SELECT id FROM attr where session_id = '".
        $session_id."';", $datatmp) == 1) {
        $sql_str = "UPDATE attr SET attr.session_id = '' WHERE id=".
        $datatmp["id"].";";
        insertRecord($sql_str);
        $sql_str = "INSERT INTO class_attr (class_id, attr_id, domtype_id, min, max, limited, session_id) VALUES(".
          $_GET["uid"].", ".
          $datatmp["id"].", 1, 0, 0, 0, '".
          $session_id."');";
        //print($sql_str);
        insertRecord($sql_str);
        //print($sql_str);
        if (getData("SELECT id FROM class_attr WHERE session_id = '".
          $session_id."';", $datatmp) == 1) {
          $sql_str = "UPDATE class_attr SET class_attr.session_id = '' WHERE id=".
          $datatmp["id"].";";
          insertRecord($sql_str);
          $contents = str_replace("%SCCSS%", "1", $contents);
        } else {
          $contents = str_replace("%SCCSS%", "-1", $contents);
          $datatmp["id"] = 0;
        }
      } else {
        $contents = str_replace("%SCCSS%", "0", $contents);
        $datatmp["id"] = 0;
      }
    } else {
      $contents = str_replace("%SCCSS%", "0", $contents);
      $datatmp["id"] = 0;
    }
  } else {
    $contents = str_replace("%SCCSS%", "0", $contents);
    $datatmp["id"] = 0;
  }
  if ($inputoutput == 1){
    $tmp_cont = str_replace("%NODE_ID%", "ia".$_GET["uid"]."ia".$datatmp["id"], $matches[1]);
    $tmp_cont = str_replace("%NODE_NM%", getMessage("Name"), $tmp_cont);
    $tmp_cont = str_replace("%IMG_TYPE%", "attr", $tmp_cont);
    $tmp_cont = str_replace("%NODE_LN%", "index.php?trg=ontoedit&amp;act=classdata&amp;sid=".
      $session_id."&amp;uid=ia".$datatmp["id"], $tmp_cont);
    $contents = str_replace($matches[0], $tmp_cont, $contents);
    $contents = str_replace("%XMLSRC%", "index.php?trg=ontoedit&amp;act=iattrlist&amp;sid=".
      $session_id."&amp;uid=c".$_GET["uid"]."&amp;sel=ia".$_GET["uid"]."ia".$datatmp["id"], $contents);
    $contents = str_replace("%ACT_ID%", "Add", $contents);
    $contents = str_replace("%PARENT%", "ia".$_GET["uid"], $contents);
  }else{
    $tmp_cont = str_replace("%NODE_ID%", "oa".$_GET["uid"]."oa".$datatmp["id"], $matches[1]);
    $tmp_cont = str_replace("%NODE_NM%", getMessage("Name"), $tmp_cont);
    $tmp_cont = str_replace("%IMG_TYPE%", "attr", $tmp_cont);
    $tmp_cont = str_replace("%NODE_LN%", "index.php?trg=ontoedit&amp;act=classdata&amp;sid=".
      $session_id."&amp;uid=oa".$datatmp["id"], $tmp_cont);
    $contents = str_replace($matches[0], $tmp_cont, $contents);
    $contents = str_replace("%XMLSRC%", "index.php?trg=ontoedit&amp;act=oattrlist&amp;sid=".
      $session_id."&amp;uid=c".$_GET["uid"]."&amp;sel=oa".$_GET["uid"]."oa".$datatmp["id"], $contents);
    $contents = str_replace("%ACT_ID%", "Add", $contents);
    $contents = str_replace("%PARENT%", "oa".$_GET["uid"], $contents);
  };
  return $contents;
}

function deleteAttr($ID, $inputoutput) {
  global $data, $path, $style, $session_id;

  $filename = $path[$style]["tpl"]."/action.xml";
  $fp = fopen($filename, "r");
  $contents = fread($fp, filesize ($filename));
  fclose ($fp);

  preg_match("/\%REPEAT\%(.*?)\%REPEAT\%/s", $contents, $matches);
  //print($data["type"]." - ".$ID[1]);
  if ($data["type"] >= 1 && isset($ID[1]) && getData("SELECT * FROM attr WHERE id = ".$ID[1].";", $a_data) > 0) {
    $sql_tmp = "SELECT type_id FROM ontology WHERE id = (SELECT onto_id FROM class WHERE id = ".$ID[0].")";
    $ontotype = Array();
    getData($sql_tmp, $ontotype);
    if (!($ontotype["type_id"] == "5")){
      $ontodata["parent_id"] = $ID[0];
      while ($ontodata["parent_id"] != 0) {
        //find class_attr line
        if (getData("SELECT * FROM class_attr WHERE attr_id = ".$ID[1].
          " AND class_id = ".$ontodata["parent_id"].";", $ca_data) > 0)
          $class_attr_data = $ca_data;
        //find parent
        if (getData("SELECT * FROM class WHERE id = ".$ontodata["parent_id"].";", $ontodata) == 0)
          $class_attr_data["class_id"] = 0;
      }
      if (isset($class_attr_data["class_id"]) && $class_attr_data["class_id"] == $ID[0]) { //attr is not inherited
        //delete from class_attr
        insertRecord("DELETE FROM class_attr WHERE attr_id=".$ID[1].";");
        //delete from attr
        insertRecord("DELETE FROM attr WHERE id=".$ID[1].";");
        //delete from term
        insertRecord("DELETE FROM term WHERE id=".$a_data["term_id"].";");
        $contents = str_replace("%SCCSS%", "1", $contents);
      }
      else
        $contents = str_replace("%SCCSS%", "0", $contents);
    }else
      $contents = str_replace("%SCCSS%", "0", $contents);
  }else{
    $contents = str_replace("%SCCSS%", "0", $contents);
    $ID[1] = 0;
  }
  $contents = str_replace($matches[0], "", $contents);
  $contents = str_replace("%ACT_ID%", "Delete", $contents);
  if ($inputoutput == 0)
    $contents = str_replace("%PARENT%", "a".$ID[0]."a".$ID[1], $contents);
  if ($inputoutput == 1)
    $contents = str_replace("%PARENT%", "ia".$ID[0]."ia".$ID[1], $contents);
  if ($inputoutput == 2)
    $contents = str_replace("%PARENT%", "oa".$ID[0]."oa".$ID[1], $contents);
  $contents = str_replace("%SELECT%", "a".$ID[0], $contents);

  return $contents;
}


function getAttrData($ID, $comment, $bound_value) {
  global $_GET, $path, $style, $session_id, $data, $term_Thing_ID, $language;

  $filename = $path[$style]["tpl"]."/attrdata.xml";
  $fp = fopen($filename, "r");
  $contents = fread($fp, filesize ($filename));
  fclose ($fp);

  preg_match("/\%REPEAT\%(.*?)\%REPEAT\%/s", $contents, $matches);
  preg_match("/\%REPDAT\%(.*?)\%REPDAT\%/s", $matches[1], $datmatches);
  preg_match("/\%REPOPT\%(.*?)\%REPOPT\%/s", $datmatches[1], $optmatches);
  $rep_cont = "";
  $attr_data = getAttrClass($ID[0], $ID[1]);
  //print("AAA");

  if ($bound_value == "true"){
    $bound="true";
  }else{
    if (isset($_GET["bound"]))
      $bound=$_GET["bound"];
    else
      $bound="false";
  };
  getData("SELECT domtype_id, min, max, limited FROM class_attr ".
          "WHERE id = ".$attr_data["attr_class_ID"].";",
          $domaindata); //domain, min, max, etc.
  getData("SELECT term.id as term_id, term.text as name, term.description as description ".
          "FROM attr, term ".
          "WHERE attr.id = ".$ID[1].
          " AND attr.term_id = term.id AND term.lang_id = ".$language["content"].
          ";",
          $ontodata); //name, descr
  getData("SELECT term.text as name, class.onto_id as onto_id FROM class, term ".
          "WHERE class.id = ".$ID[0].
          " AND class.term_id = term.id AND term.lang_id = ".$language["content"].
          ";",
          $contodata); //current class
  $contodata["name"] = htmlspecialchars($contodata["name"]);
  if ($ID[0] != $attr_data["classID"])
    getData("SELECT term.text as name FROM class, term ".
            "WHERE class.id = ".$attr_data["classID"].
            " AND class.term_id = term.id AND term.lang_id = ".$language["content"].
            ";",
            $iontodata); //class the attribute is inherited from
  getData("SELECT term.text as name FROM ontology, term ".
          "WHERE ontology.id = ".$contodata["onto_id"].
          " AND ontology.term_id = term.id AND term.lang_id = ".$language["content"].
          ";",
          $pontodata); //current ontology


  $sql_tmp = "SELECT LeftBound, RightBound FROM CAD_Bounds WHERE ClassID=".$ID[0]." and AttrID=".$ID[1]." and Type=1";
  $rec_bound = Array();
  getData($sql_tmp, $rec_bound);

  $sql_tmp = "SELECT LeftBound, RightBound FROM CAD_Bounds WHERE ClassID=".$ID[0]." and AttrID=".$ID[1]." and Type=2";
  $fe_bound = Array();
  getData($sql_tmp, $fe_bound);
//echo "SELECT domtype.id as id, term.text as name FROM domtype, term WHERE domtype.term_id = term.id AND term.lang_id = ".$language["content"].";";
  $i_max = getMultData("SELECT domtype.id as id, term.text as name FROM domtype, term ".
        "WHERE domtype.term_id = term.id AND term.lang_id = ".$language["content"].";",
        $domtypes); //possible domains

  $udata = "";

  if ($data["type"] >= 1) { //user
    //New name
    $contents = str_replace("%NAME%", $ontodata["name"], $contents);
    //Class Name
    $classlb = str_replace($optmatches[0], "", $datmatches[1]);
    $classlb = str_replace("%TYPE%", "Label", $classlb);
    $classlb = str_replace("%NODE_ID%", "cname", $classlb);
    $classlb = str_replace("%NODE_TL%", getMessage("Class Name"), $classlb);
    $classlb = str_replace("%VALUE%", $contodata["name"], $classlb);

    if ($ID[0] != $attr_data["classID"]) { //inherited attribute
      //Parent Class Name
      $iclasslb = str_replace($optmatches[0], "", $datmatches[1]);
      $iclasslb = str_replace("%TYPE%", "Label", $iclasslb);
      $iclasslb = str_replace("%NODE_ID%", "iname", $iclasslb);
      $iclasslb = str_replace("%NODE_TL%", getMessage("Inherited From"), $iclasslb);
      $iclasslb = str_replace("%VALUE%", $iontodata["name"], $iclasslb);
      //Domain
      $utype = str_replace($optmatches[0], "", $datmatches[1]);
      $utype = str_replace("%TYPE%", "Label", $utype);
      $utype = str_replace("%NODE_ID%", "otype", $utype);
      $utype = str_replace("%NODE_TL%", getMessage("Domain"), $utype);
      $domain = "";
      for ($i = 0; $i < $i_max; $i++) {
        if ($domaindata["domtype_id"] == $domtypes[$i]["id"]) {
          $domain = $domtypes[$i]["name"];
          break;
        }
      }
      $utype = str_replace("%VALUE%", $domain, $utype);
      //Name
      $fname = str_replace($optmatches[0], "", $datmatches[1]);
      $fname = str_replace("%TYPE%", "Label", $fname);
      $fname = str_replace("%NODE_ID%", "oname", $fname);
      $fname = str_replace("%NODE_TL%", getMessage("Name"), $fname);
      $fname = str_replace("%VALUE%", $ontodata["name"], $fname);
      //Description
      $lname = str_replace($optmatches[0], "", $datmatches[1]);
      $lname = str_replace("%TYPE%", "Label", $lname);
      $lname = str_replace("%NODE_ID%", "odescr", $lname);
      $lname = str_replace("%NODE_TL%", getMessage("Description"), $lname);
      $lname = str_replace("%VALUE%", $ontodata["description"], $lname);

      // get list of enumerable domains from DB
      $sql = "SELECT id, CollectionItem FROM domtype_collection WHERE class_attr_id = ".$attr_data["attr_class_ID"]." and lang_id = ".$language["content"];
      $i_max = getMultData($sql, $CollectionDomains);
      // list of enumerable domains
      $opts = "";
      for ($i = 0; $i < $i_max; $i++) {
        $opt = str_replace("%OPT_ID%", $CollectionDomains[$i]["id"], $optmatches[1]);
        $opt = str_replace("%OPT_TL%", $CollectionDomains[$i]["CollectionItem"], $opt);
        if ($i == 0)
          $opt = str_replace("%SELECTED%", "selected", $opt);
        else
          $opt = str_replace("%SELECTED%", "0", $opt);
        $opts .= $opt;
      }
      //domain
      $edomain = str_replace($optmatches[0], $opts, $datmatches[1]);
      $edomain = str_replace("%TYPE%", "ListBox", $edomain);
      $edomain = str_replace("%NODE_ID%", "olistbox", $edomain);
      $edomain = str_replace("%NODE_TL%", getMessage("List of enumerable domains"), $edomain);

      //button
      if ($bound == "true"){
        //button
        $ubutn = str_replace($optmatches[0], "", $datmatches[1]);
        $ubutn = str_replace("%TYPE%", "Button", $ubutn);
        $ubutn = str_replace("%NODE_ID%", "obutn", $ubutn);
        $ubutn = str_replace("%NODE_TL%", getMessage("Save"), $ubutn);
        $ubutn = str_replace("%VALUE%", "'0', 'oFeasibleMin', 'oRecomendedMin', 'oRecomendedMax', 'oFeasibleMax'", $ubutn);
      }else{
        $ubutn = "";
      };
    }else {
      //Parent Class Name
      $iclasslb = "";
      //Domain
      //options
      $opts = "";
      for ($i = 0; $i < $i_max; $i++) {
        $opt = str_replace("%OPT_ID%", $domtypes[$i]["id"], $optmatches[1]);
        $opt = str_replace("%OPT_TL%", $domtypes[$i]["name"], $opt);
        if ($domaindata["domtype_id"] == $domtypes[$i]["id"])
          $opt = str_replace("%SELECTED%", "selected", $opt);
        else
          $opt = str_replace("%SELECTED%", "0", $opt);
        $opts .= $opt;
      }
      //domain
      $utype = str_replace($optmatches[0], $opts, $datmatches[1]);
      $utype = str_replace("%TYPE%", "Option", $utype);
      $utype = str_replace("%NODE_ID%", "otype", $utype);
      $utype = str_replace("%NODE_TL%", getMessage("Domain"), $utype);
      //Name
      $fname = str_replace($optmatches[0], "", $datmatches[1]);
      $fname = str_replace("%TYPE%", "Text", $fname);
      $fname = str_replace("%NODE_ID%", "oname", $fname);
      $fname = str_replace("%NODE_TL%", getMessage("Name"), $fname);
      $fname = str_replace("%VALUE%", $ontodata["name"], $fname);
      //Description
      $lname = str_replace($optmatches[0], "", $datmatches[1]);
      $lname = str_replace("%TYPE%", "Text", $lname);
      $lname = str_replace("%NODE_ID%", "odescr", $lname);
      $lname = str_replace("%NODE_TL%", getMessage("Description"), $lname);
      $lname = str_replace("%VALUE%", $ontodata["description"], $lname);

      // get list of enumerable domains from DB
      $sql = "SELECT id, CollectionItem FROM domtype_collection WHERE lang_id = ".$language["content"]." and class_attr_id = (select id from class_attr WHERE class_id = ".$ID[0]." and attr_id = ".$ID[1].")";
      $i_max = getMultData($sql, $CollectionDomains);

      //button save
      $ubutn = str_replace($optmatches[0], "", $datmatches[1]);
      $ubutn = str_replace("%TYPE%", "Button", $ubutn);
      $ubutn = str_replace("%NODE_ID%", "obutn", $ubutn);
      $ubutn = str_replace("%NODE_TL%", getMessage("Save"), $ubutn);
      $ubutn = str_replace("%VALUE%", "'0', 'oname', 'odescr', 'otype'", $ubutn);

      // list of enumerable domains
      $opts = "";
      for ($i = 0; $i < $i_max; $i++) {
        $opt = str_replace("%OPT_ID%", $CollectionDomains[$i]["id"], $optmatches[1]);
        $opt = str_replace("%OPT_TL%", $CollectionDomains[$i]["CollectionItem"], $opt);
        if ($i == 0)
          $opt = str_replace("%SELECTED%", "selected", $opt);
        else
          $opt = str_replace("%SELECTED%", "0", $opt);
        $opts .= $opt;
      }
      //domain
      $edomain = str_replace($optmatches[0], $opts, $datmatches[1]);
      $edomain = str_replace("%TYPE%", "ListBox", $edomain);
      $edomain = str_replace("%NODE_ID%", "olistbox", $edomain);
      $edomain = str_replace("%NODE_TL%", getMessage("List of enumerable domains"), $edomain);

      //Edit for unm domain
      $editenum = str_replace($optmatches[0], "", $datmatches[1]);
      $editenum = str_replace("%TYPE%", "Text", $editenum);
      $editenum = str_replace("%NODE_ID%", "onewdom", $editenum);
      $editenum = str_replace("%NODE_TL%", getMessage("Add following enumerable domain"), $editenum);
      $editenum = str_replace("%VALUE%", $ontodata["name"], $editenum);

      //button add
      $ubutnadd = str_replace($optmatches[0], "", $datmatches[1]);
      $ubutnadd = str_replace("%TYPE%", "Button", $ubutnadd);
      $ubutnadd = str_replace("%NODE_ID%", "obutnAdd", $ubutnadd);
      $ubutnadd = str_replace("%NODE_TL%", getMessage("Add"), $ubutnadd);
      $ubutnadd = str_replace("%VALUE%", "'0', 'onewdom'", $ubutnadd);

      //button delete
      $ubutndelete = str_replace($optmatches[0], "", $datmatches[1]);
      $ubutndelete = str_replace("%TYPE%", "Button", $ubutndelete);
      $ubutndelete = str_replace("%NODE_ID%", "obutnDelete", $ubutndelete);
      $ubutndelete = str_replace("%NODE_TL%", getMessage("Delete"), $ubutndelete);
      $ubutndelete = str_replace("%VALUE%", "'0', 'olistbox'", $ubutndelete);

    }

    if ($bound == "true"){
      //Bound
      $ubnd = str_replace($optmatches[0], "", $datmatches[1]);
      $ubnd = str_replace("%TYPE%", "Label", $ubnd);
      $ubnd = str_replace("%NODE_ID%", "odescr", $ubnd);
      $ubnd = str_replace("%NODE_TL%", getMessage("Fuzy")." ".getMessage("Interval"), $ubnd);
      $ubnd = str_replace("%VALUE%", "", $ubnd);

      //Feasible min
      $ufemin = str_replace($optmatches[0], "", $datmatches[1]);
      $ufemin = str_replace("%TYPE%", "Text", $ufemin);
      $ufemin = str_replace("%NODE_ID%", "oFeasibleMin", $ufemin);
      $ufemin = str_replace("%NODE_TL%", getMessage("Feasible min"), $ufemin);
      $ufemin = str_replace("%VALUE%", $fe_bound["LeftBound"], $ufemin);

      //Recomended min
      $urecmin = str_replace($optmatches[0], "", $datmatches[1]);
      $urecmin = str_replace("%TYPE%", "Text", $urecmin);
      $urecmin = str_replace("%NODE_ID%", "oRecomendedMin", $urecmin);
      $urecmin = str_replace("%NODE_TL%", getMessage("Recomended min"), $urecmin);
      $urecmin = str_replace("%VALUE%", $rec_bound["LeftBound"], $urecmin);

      //Recomended max
      $urecmax = str_replace($optmatches[0], "", $datmatches[1]);
      $urecmax = str_replace("%TYPE%", "Text", $urecmax);
      $urecmax = str_replace("%NODE_ID%", "oRecomendedMax", $urecmax);
      $urecmax = str_replace("%NODE_TL%", getMessage("Recomended max"), $urecmax);
      $urecmax = str_replace("%VALUE%", $rec_bound["RightBound"], $urecmax);

      //Feasible max
      $ufemax = str_replace($optmatches[0], "", $datmatches[1]);
      $ufemax = str_replace("%TYPE%", "Text", $ufemax);
      $ufemax = str_replace("%NODE_ID%", "oFeasibleMax", $ufemax);
      $ufemax = str_replace("%NODE_TL%", getMessage("Feasible max"), $ufemax);
      $ufemax = str_replace("%VALUE%", $fe_bound["RightBound"], $ufemax);
    }else{
      $ubnd="";
      $urecmin="";
      $urecmax="";
      $ufemin="";
      $ufemax="";
    };

    //Ontology Name
    $ontolb = str_replace($optmatches[0], "", $datmatches[1]);
    $ontolb = str_replace("%TYPE%", "Label", $ontolb);
    $ontolb = str_replace("%NODE_ID%", "lname", $ontolb);
    $ontolb = str_replace("%NODE_TL%", getMessage("Ontology Name"), $ontolb);
    $ontolb = str_replace("%VALUE%", $pontodata["name"], $ontolb);
    //Label
    $lablttt = str_replace($optmatches[0], "", $datmatches[1]);
    $lablttt = str_replace("%TYPE%", "Label", $lablttt);
    $lablttt = str_replace("%NODE_ID%", "", $lablttt);
    if ($comment != "") $lablttt = str_replace("%NODE_TL%", getMessage("Error"), $lablttt);
    else $lablttt = str_replace("%NODE_TL%", "", $lablttt);
    $lablttt = str_replace("%VALUE%", $comment, $lablttt);
    //User
    $udata = str_replace($datmatches[0], $classlb.$iclasslb.$ontolb.$fname.$lname.$lablttt.$ubnd.$ufemin.$urecmin.$urecmax.$ufemax, $matches[1]);
    $udata = str_replace("%GROUP_ID%", "0", $udata);
    $udata = str_replace("%GROUP_TL%", getMessage("Attribute data"), $udata);

    // Domain group
    $domaindata = str_replace($datmatches[0], $utype.$ubutn.$edomain.$editenum.$ubutnadd.$ubutndelete, $matches[1]);
    $domaindata = str_replace("%GROUP_ID%", "2", $domaindata);
    $domaindata = str_replace("%GROUP_TL%", getMessage("Domain data"), $domaindata);
    //print "****".$udata."****";

//Action
    $btn1 = str_replace($optmatches[0], "", $datmatches[1]);
    $btn1 = str_replace("%TYPE%", "Button", $btn1);
    $btn1 = str_replace("%NODE_ID%", "", $btn1);
    $btn1 = str_replace("%NODE_TL%", getMessage("Ontologies"), $btn1);
    $btn1 = str_replace("%VALUE%", "'wd_tree', 'index.php?trg=ontoedit&amp;sid=".
      $session_id."&amp;act=ontolist&amp;sel=".$contodata["onto_id"]."'", $btn1);

    if (isset($fe_bound["LeftBound"]) && isset($rec_bound["LeftBound"]) && isset($fe_bound["RightBound"]) && isset($rec_bound["RightBound"])){
      $btn2 = str_replace($optmatches[0], "", $datmatches[1]);
      $btn2 = str_replace("%TYPE%", "Button", $btn2);
      $btn2 = str_replace("%NODE_ID%", "", $btn2);
      $btn2 = str_replace("%NODE_TL%", getMessage("Bound"), $btn2);
      $btn2 = str_replace("%VALUE%", "'new_wnd', 'img.php?x1=".$fe_bound["LeftBound"]."&amp;x2=".$rec_bound["LeftBound"].
        "&amp;x3=".$rec_bound["RightBound"]."&amp;x4=".$fe_bound["RightBound"]."&amp;width=500'", $btn2);
    }else{
      $btn2 = "";
    };

    $btns = str_replace($datmatches[0], $btn1.$btn2, $matches[1]);
    $btns = str_replace("%GROUP_ID%", "1", $btns);
    $btns = str_replace("%GROUP_TL%", getMessage("Action"), $btns);

  }
  else { //guest
    //New name
    $contents = str_replace("%NAME%", $ontodata["name"], $contents);
    //Name
    $fname = str_replace($optmatches[0], "", $datmatches[1]);
    $fname = str_replace("%TYPE%", "Label", $fname);
    $fname = str_replace("%NODE_ID%", "oname", $fname);
    $fname = str_replace("%NODE_TL%", getMessage("Name"), $fname);
    $fname = str_replace("%VALUE%", $ontodata["name"], $fname);
    //Description
    $lname = str_replace($optmatches[0], "", $datmatches[1]);
    $lname = str_replace("%TYPE%", "Label", $lname);
    $lname = str_replace("%NODE_ID%", "odescr", $lname);
    $lname = str_replace("%NODE_TL%", getMessage("Description"), $lname);
    $lname = str_replace("%VALUE%", $ontodata["description"], $lname);
    //User
    $udata = str_replace($datmatches[0], $fname.$lname, $matches[1]);
    $udata = str_replace("%GROUP_ID%", "0", $udata);
    $udata = str_replace("%GROUP_TL%", getMessage("Attribute data"), $udata);
    //print "****".$udata."****";
  }
  return str_replace($matches[0], $udata.$domaindata.$btns, $contents);
}

function Compare($ar1, $ar2)
{
  $res = strcasecmp($ar1['name'], $ar2['name']);
  if ($res < 0) return -1;
  else if ($res > 0) return 1;
  return 0;
}

?>